<script setup>
import {ref, computed} from 'vue';

// 定义 props
const props = defineProps({
  total: {
    type: Number,
    required: true
  },
  size: {
    type: Number,
    default: 8,
  },
  page: {
    type: Number,
    default: 1
  }
});

// 计算总页数
const totalPages = computed(() => Math.ceil(props.total / props.size));

// 计算要显示的页面范围
const displayedPages = computed(() => {
  const pages = [];
  const startPage = Math.max(1, props.page - 2);
  const endPage = Math.min(totalPages.value, props.page + 2);
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }
  return pages;
});

// 定义 emit
const emit = defineEmits(['change']);

// 页面跳转函数
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    emit('change', page);
  }
};
</script>
<template>
  <div class="pagination">
    <button @click="goToPage(1)" :disabled="page === 1">首页</button>
    <button @click="goToPage(page - 1)" :disabled="page === 1">上一页</button>
    <template v-for="(v,k) in displayedPages" :key="k">
      <button
          @click="goToPage(v)"
          :class="{ active: v === page }"
          :disabled="page === v"
      >
        {{ v }}
      </button>
    </template>
    <button @click="goToPage(page + 1)" :disabled="page === totalPages">下一页</button>
    <button @click="goToPage(totalPages)" :disabled="page === totalPages">末页</button>
  </div>
</template>


<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  margin: 5px;
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #fff;
  color: #333;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.pagination button:hover {
  background-color: #007BFF;
  color: #fff;
}

.pagination button.active {
  background-color: #007BFF;
  color: #fff;
  border: 1px solid #007BFF;
}

.pagination button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
  background-color: #eee;
  color: #aaa;
}
</style>